"ui";
ui.layout(
    <vertical h="*">
        <horizontal h="{{parseInt(device.height/4)}}px" gravity="center">
            <img id="boardOrigin" w="*" h="*" />
        </horizontal>
        <horizontal h="{{parseInt(device.height/4)}}px" gravity="center">
            <img id="board" w="*" h="*" />
        </horizontal>
        <button style="Widget.AppCompat.Button.Colored" text="选择图片" id="chooseImg" />
        <card w="*" h="36" marginLeft="10" marginRight="10" marginBottom="5" marginTop="30" cardCornerRadius="13dp" cardElevation="0dp" backgroundTint="#88ffffff">
            <RelativeLayout  marginLeft="10" marginRight="5">
                <text id="text" textColor="black" textSize="16sp" marginTop="6" text="阈值" layout_alignParentLeft="true"/>
                <text id="progress_text" w="35" h="30" textColor="black" textSize="16sp" text="0" marginTop="6" marginLeft="40" />
                <seekbar id="progress" progress="0" w="*" marginTop="8" marginLeft="60" layout_toRightOf="@id/progress_value1" />
            </RelativeLayout>
        </card>
    </vertical>
);

let img, imgGray, imgSrc;
events.on('exit', function () {
    img && img.recycle();
    imgGray && imgGray.recycle();
    imgSrc && imgSrc.recycle();
});

let ResultIntent = {
    intentCallback: {},
    init: function() {
        activity.getEventEmitter().on("activity_result", (requestCode, resultCode, data) => {
            this.onActivityResult(requestCode, resultCode, data);
        });
    },
    startActivityForResult: function(intent, callback) {
        var i;
        for (i = 0; i < 65536; i++) {
            if (!(i in this.intentCallback)) break;
        }
        if (i >= 65536) {
            toast("启动Intent失败：同时请求的Intent过多");
            return;
        }
        this.intentCallback[i] = callback;
        activity.startActivityForResult(intent, i);
    },
    onActivityResult: function(requestCode, resultCode, data) {
        var cb = this.intentCallback[requestCode];
        if (!cb) return;
        delete this.intentCallback[requestCode];
        cb(resultCode, data);
    }
};
ResultIntent.init();

ui.chooseImg.on('click', function() {
    let it = new android.content.Intent(android.content.Intent.ACTION_GET_CONTENT);
    it.setType('image/*');
    ResultIntent.startActivityForResult(it, function (resultCode, data) {
        if (resultCode != activity.RESULT_OK) return;
        
        let filePathColumn = [android.provider.MediaStore.Images.Media.DATA];
        let cursor = activity.getContentResolver().query(
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            filePathColumn,
            '_id=?',
            [String(android.provider.DocumentsContract.getDocumentId(data.getData())).split(":")[1]],
            null);
        if (cursor && cursor.moveToFirst()) {
            let picturePath = cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
            console.log(picturePath);
            cursor.close();
            imgSrc && imgSrc.recycle();
            imgSrc = images.read(picturePath);
            ui.run(function () {
                ui.boardOrigin.setImageBitmap(imgSrc.getBitmap());
            });
            let scale1 = ui.board.getWidth() / imgSrc.getWidth();
            let scale2 = ui.board.getHeight() / imgSrc.getHeight();
            let toScale = scale1;
            toScale = Math.min(scale1, scale2);
            let imgScaled = images.scale(imgSrc, toScale, toScale);
            imgGray && imgGray.recycle();
            imgGray = images.grayscale(imgScaled);
            imgScaled.recycle();
            imgThreshold();
        }
    });
});

// 节流
function throttle(fn, delay){
    let valid = true
    return function() {
       if(!valid){
           //休息时间 暂不接客
           return false 
       }
       // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
            fn()
            valid = true;
        }, delay)
    }
}

// 启动一个处理图片的线程
let imgProcess = threads.start(function() {
    setInterval(() => {}, 1000);
});


let seekBarEvent = throttle(function () {
    imgThreshold()
}, 50);

ui['progress'].setOnSeekBarChangeListener(new android.widget.SeekBar.OnSeekBarChangeListener({
    onProgressChanged: function(seekbar, i, b) {
        ui['progress_text'].text('' + parseInt(i * 255 / 100));
        seekBarEvent();
    }
}));


function imgThreshold() {
    if (imgGray && !imgGray.isRecycled()) {
        imgProcess.setTimeout(function (){
            img && img.recycle();
            img = images.threshold(imgGray, parseInt(ui['progress'].getProgress() * 255 /100), 255);
            ui.run(function () {
                ui.board.setImageBitmap(img.getBitmap());
            })
        }, 0);
    }
}
